<template>
	<div class="wrapper">
		<!-- 顶部应用栏 -->
		<header class="mdc-top-app-bar">
			<div class="mdc-top-app-bar__row">
				<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
					<BackButton />
					<h1 class="mdc-top-app-bar__title">还款</h1>
				</section>
			</div>
		</header>

		<!-- 还款表单 -->
		<div class="repay-form">
			<!-- 透支信息显示 -->
			<div class="overdraft-display">
				<p class="overdraft-label">当前透支金额</p>
				<p class="overdraft-amount">¥{{ currentOverdraftAmount }}</p>
			</div>

			<!-- 还款金额输入 -->
			<div class="form-group">
				<label>还款金额</label>
				<div class="input-wrapper">
					<span class="currency">¥</span>
					<input 
						type="number" 
						v-model="amount" 
						placeholder="请输入还款金额"
						@input="validateAmount"
						min="0"
						step="0.01"
					/>
				</div>
				<p class="hint">最多可还：¥{{ maxRepayAmount.toFixed(2) }}</p>
				<p class="warning" v-if="amount && parseFloat(amount) > maxRepayAmount">
					还款金额不能超过当前透支金额（¥{{ currentOverdraftAmount }}）
				</p>
			</div>

			<!-- 快捷金额选择 -->
			<div class="quick-amounts">
				<h3 class="section-title">快捷金额</h3>
				<div class="amount-buttons">
					<button 
						v-for="quickAmount in quickAmounts" 
						:key="quickAmount"
						class="amount-btn"
						:class="{ active: amount == quickAmount }"
						@click="selectAmount(quickAmount)"
						:disabled="quickAmount > currentOverdraftAmountNum"
					>
						¥{{ quickAmount }}
					</button>
					<!-- 全部还款按钮 -->
					<button 
						class="amount-btn full-repay-btn"
						:class="{ active: amount == currentOverdraftAmountNum }"
						@click="selectAmount(currentOverdraftAmountNum)"
						:disabled="currentOverdraftAmountNum <= 0"
					>
						全部还款 ¥{{ currentOverdraftAmount }}
					</button>
				</div>
			</div>

			<!-- 还款说明 -->
			<div class="repay-info">
				<h3 class="section-title">还款说明</h3>
				<ul>
					<li>还款金额不能超过当前透支金额</li>
					<li>还款成功后，透支额度将立即恢复</li>
					<li>建议及时还款，避免产生额外利息</li>
				</ul>
			</div>

			<!-- 提交按钮 -->
			<div class="submit-section">
				<button class="submit-btn" @click="submitRepay" :disabled="!isValid || loading">
					<span v-if="loading">还款中...</span>
					<span v-else>确认还款</span>
				</button>
			</div>
		</div>

		<!-- 底部菜单部分 -->
		<AppFooter></AppFooter>
	</div>
</template>

<script>
	import AppFooter from '../components/AppFooter.vue';
	import BackButton from '../components/BackButton.vue';
	export default {
		name: 'WalletRepay',
		data() {
			return {
				amount: '',
				loading: false,
				currentOverdraftAmount: '0.00',
				quickAmounts: [50, 100, 200, 500],
				user: null
			}
		},
		computed: {
			// 当前透支金额（数字格式）
			currentOverdraftAmountNum() {
				return parseFloat(this.currentOverdraftAmount || '0') || 0;
			},
			// 最多可还金额（等于当前透支金额）
			maxRepayAmount() {
				return this.currentOverdraftAmountNum;
			},
			isValid() {
				if (!this.amount || this.amount.trim() === '') return false;
				const num = parseFloat(this.amount);
				if (isNaN(num) || num <= 0) return false;
				// 还款金额不能超过当前透支金额
				return num <= this.currentOverdraftAmountNum && this.currentOverdraftAmountNum > 0;
			}
		},
		created() {
			let user = this.$getSessionStorage('user');
			if (user == null) {
				this.$router.push('/login');
				return;
			}
			this.user = user;
			this.loadWalletInfo();
		},
		methods: {
			loadWalletInfo() {
				this.$axios.post('wallet/info', this.$qs.stringify({
					walletId: this.user.userId
				})).then(response => {
					// 兼容不同的响应码格式（200 或 '200'）
					if (response.data && (response.data.code === 200 || response.data.code === '200')) {
						const result = response.data.result || {};
						
						// 调试：打印返回的数据
						console.log('钱包信息:', result);
						console.log('当前透支金额字段:', result.currentOverdraftAmount);
						
						// 读取当前透支金额（与 MyWallet.vue 保持一致）
						const overdraftAmountStr = result.currentOverdraftAmount || '0.00';
						
						// 确保当前透支金额格式正确（保留两位小数）
						const overdraftAmount = parseFloat(overdraftAmountStr) || 0;
						this.currentOverdraftAmount = overdraftAmount.toFixed(2);
						
						console.log('解析后的当前透支金额:', this.currentOverdraftAmount, '原始值:', overdraftAmountStr);
						
						// 如果当前透支金额为0或负数，提示并返回
						if (overdraftAmount <= 0) {
							this.$toast?.info('当前无透支金额，无需还款');
							setTimeout(() => {
								this.$router.go(-1);
							}, 1500);
						}
					} else {
						const errorMsg = response.data?.message || '获取钱包信息失败';
						console.error('获取钱包信息失败，响应码:', response.data?.code, '错误信息:', errorMsg);
						this.$toast?.error(errorMsg);
					}
				}).catch(error => {
					console.error('获取钱包信息失败:', error);
					console.error('错误详情:', error.response?.data);
					const errorMsg = error.response?.data?.message || error.message || '获取钱包信息失败，请稍后重试';
					this.$toast?.error(errorMsg);
				});
			},
			selectAmount(amount) {
				// 确保金额不超过当前透支金额
				const maxAmount = this.currentOverdraftAmountNum;
				if (amount > maxAmount) {
					this.$toast?.error(`还款金额不能超过当前透支金额（¥${this.currentOverdraftAmount}）`);
					// 如果超过，自动设置为最大可还金额
					this.amount = maxAmount.toFixed(2);
				} else {
					this.amount = amount.toString();
				}
				this.validateAmount();
			},
			validateAmount() {
				if (!this.amount) return;
				const num = parseFloat(this.amount);
				const maxAmount = this.currentOverdraftAmountNum;
				if (num <= 0) {
					this.$toast?.error('还款金额必须大于0');
				} else if (num > maxAmount) {
					this.$toast?.error(`还款金额不能超过当前透支金额（¥${this.currentOverdraftAmount}）`);
				}
			},
			submitRepay() {
				if (!this.isValid) {
					if (!this.amount || parseFloat(this.amount) <= 0) {
						this.$toast?.error('请输入有效的还款金额');
					} else {
						const num = parseFloat(this.amount);
						const maxAmount = this.currentOverdraftAmountNum;
						if (num > maxAmount) {
							this.$toast?.error(`还款金额不能超过当前透支金额（¥${this.currentOverdraftAmount}）`);
						}
					}
					return;
				}

				const repayAmount = parseFloat(this.amount);
				const maxAmount = this.currentOverdraftAmountNum;
				
				// 再次验证，确保不超过最大可还金额
				if (repayAmount > maxAmount) {
					this.$toast?.error(`还款金额不能超过当前透支金额（¥${this.currentOverdraftAmount}）`);
					return;
				}
				
				if (!confirm(`确认还款 ¥${repayAmount.toFixed(2)} 吗？`)) {
					return;
				}

				this.loading = true;
				this.$axios.post('wallet/repay', this.$qs.stringify({
					walletId: this.user.userId,
					amount: repayAmount
				})).then(response => {
					if (response.data && (response.data.code === 200 || response.data.code === '200')) {
						this.$toast?.success('还款成功！');
						setTimeout(() => {
							this.$router.go(-1);
						}, 1500);
					} else {
						this.$toast?.error(response.data.message || '还款失败');
					}
				}).catch(error => {
					console.error(error);
					this.$toast?.error('还款失败，请稍后重试');
				}).finally(() => {
					this.loading = false;
				});
			}
		},
		components: {
			AppFooter,
			BackButton
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 顶部应用栏 */
	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/****************** 还款表单 ******************/
	.repay-form {
		margin-top: 0;
		padding: 4vw;
	}

	.overdraft-display {
		background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
		border-radius: 12px;
		padding: 6vw;
		text-align: center;
		margin-bottom: 4vw;
		color: #fff;
		box-shadow: 0 4px 12px rgba(0,0,0,0.1);
	}

	.overdraft-label {
		font-size: 3.5vw;
		opacity: 0.9;
		margin-bottom: 2vw;
	}

	.overdraft-amount {
		font-size: 8vw;
		font-weight: bold;
		margin: 0;
	}

	.form-group {
		background-color: #fff;
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.form-group label {
		display: block;
		font-size: 3.5vw;
		color: #666;
		margin-bottom: 3vw;
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		border: 2px solid #e0e0e0;
		border-radius: 8px;
		padding: 3vw;
		transition: border-color 0.3s;
	}

	.input-wrapper:focus-within {
		border-color: #0097FF;
	}

	.currency {
		font-size: 5vw;
		color: #333;
		margin-right: 2vw;
		font-weight: 500;
	}

	.input-wrapper input {
		flex: 1;
		border: none;
		outline: none;
		font-size: 4.5vw;
		color: #333;
	}

	.hint {
		margin-top: 2vw;
		font-size: 3vw;
		color: #ff9800;
	}

	.warning {
		margin-top: 2vw;
		font-size: 3vw;
		color: #f44336;
	}

	/****************** 快捷金额 ******************/
	.quick-amounts {
		background-color: #fff;
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.section-title {
		font-size: 4vw;
		color: #666;
		margin: 0 0 3vw 0;
		font-weight: 500;
	}

	.amount-buttons {
		display: flex;
		flex-wrap: wrap;
		gap: 2vw;
	}

	.amount-btn {
		flex: 1;
		min-width: calc(50% - 1vw);
		padding: 3vw;
		border: 2px solid #e0e0e0;
		border-radius: 8px;
		background-color: #fff;
		color: #333;
		font-size: 4vw;
		cursor: pointer;
		transition: all 0.3s;
	}

	.amount-btn:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

	.amount-btn.active {
		border-color: #0097FF;
		background-color: #0097FF;
		color: #fff;
	}

	.amount-btn:active:not(:disabled) {
		transform: scale(0.95);
	}

	.amount-btn.full-repay-btn {
		width: 100%;
		min-width: 100%;
		margin-top: 2vw;
		background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
		color: #fff;
		font-weight: 600;
	}

	.amount-btn.full-repay-btn.active {
		background: linear-gradient(135deg, #f57c00 0%, #e65100 100%);
		border-color: #e65100;
	}

	/****************** 还款说明 ******************/
	.repay-info {
		background-color: #fff;
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.repay-info ul {
		margin: 0;
		padding-left: 5vw;
	}

	.repay-info li {
		font-size: 3.5vw;
		color: #666;
		line-height: 1.8;
		margin-bottom: 1.5vw;
	}

	/****************** 提交按钮 ******************/
	.submit-section {
		padding: 4vw;
	}

	.submit-btn {
		width: 100%;
		padding: 4vw;
		background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
		color: #fff;
		border: none;
		border-radius: 12px;
		font-size: 4.5vw;
		cursor: pointer;
		transition: all 0.3s;
		box-shadow: 0 4px 12px rgba(255, 152, 0, 0.4);
	}

	.submit-btn:disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.submit-btn:active:not(:disabled) {
		transform: scale(0.98);
	}
</style>

